package com.riche.codefactory.controller;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.riche.codefactory.annotation.AuthCheck;
import com.riche.codefactory.common.BaseResponse;
import com.riche.codefactory.common.DeleteRequest;
import com.riche.codefactory.common.ErrorCode;
import com.riche.codefactory.common.R;
import com.riche.codefactory.constant.UserConstant;
import com.riche.codefactory.exception.BusinessException;
import com.riche.codefactory.exception.ThrowUtils;
import com.riche.codefactory.model.c2s.question.*;
import com.riche.codefactory.model.domain.Question;
import com.riche.codefactory.model.domain.User;
import com.riche.codefactory.model.s2c.S2cQuestion;
import com.riche.codefactory.service.IQuestionSVC;
import com.riche.codefactory.service.IUserSVC;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 题目接口
 *
 */
@RestController
@RequestMapping("/question")
@Slf4j
public class QuestionController {

    @Resource
    private IQuestionSVC questionSVC;

    @Resource
    private IUserSVC userService;

    // region 增删改查

    /**
     * 创建题目
     *
     * @param c2sQuestionAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Long> addQuestion(@RequestBody C2sQuestionAddRequest c2sQuestionAddRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(c2sQuestionAddRequest == null, ErrorCode.PARAMS_ERROR);
        // todo 在此处将实体类和 DTO 进行转换
        Question question = new Question();
        BeanUtils.copyProperties(c2sQuestionAddRequest, question);
        List<String> tags = c2sQuestionAddRequest.getTags();
        if (tags != null) {
            question.setTags(JSONUtil.toJsonStr(tags));
        }
        // 数据校验
        questionSVC.validQuestion(question, true);
        // todo 填充默认值
        User loginUser = userService.getLoginUser(request);
        question.setUserId(loginUser.getId());
        // 写入数据库
        boolean result = questionSVC.save(question);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        // 返回新写入的数据 id
        long newQuestionId = question.getId();
        return R.ok(newQuestionId);
    }

    /**
     * 删除题目
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> deleteQuestion(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        Question oldQuestion = questionSVC.getById(id);
        ThrowUtils.throwIf(oldQuestion == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!oldQuestion.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 操作数据库
        boolean result = questionSVC.removeById(id);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return R.ok(true);
    }

    /**
     * 更新题目（仅管理员可用）
     *
     * @param c2sQuestionUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateQuestion(@RequestBody C2sQuestionUpdateRequest c2sQuestionUpdateRequest) {
        if (c2sQuestionUpdateRequest == null || c2sQuestionUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // todo 在此处将实体类和 DTO 进行转换
        Question question = new Question();
        BeanUtils.copyProperties(c2sQuestionUpdateRequest, question);
        List<String> tags = c2sQuestionUpdateRequest.getTags();
        if (tags != null) {
            question.setTags(JSONUtil.toJsonStr(tags));
        }

        // 数据校验
        questionSVC.validQuestion(question, false);
        // 判断是否存在
        long id = c2sQuestionUpdateRequest.getId();
        Question oldQuestion = questionSVC.getById(id);
        ThrowUtils.throwIf(oldQuestion == null, ErrorCode.NOT_FOUND_ERROR);
        // 操作数据库
        boolean result = questionSVC.updateById(question);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return R.ok(true);
    }

    /**
     * 根据 id 获取题目（封装类）
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<S2cQuestion> getQuestionVOById(long id, HttpServletRequest request) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Question question = questionSVC.getById(id);
        ThrowUtils.throwIf(question == null, ErrorCode.NOT_FOUND_ERROR);
        // 获取封装类
        return R.ok(questionSVC.getQuestionVO(question, request));
    }

    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<Question>> listQuestionByPage(@RequestBody C2sQuestionQueryRequest c2sQuestionQueryRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(c2sQuestionQueryRequest == null, ErrorCode.PARAMS_ERROR);
        Page<Question> questionPage = questionSVC.listQuestionByPage(c2sQuestionQueryRequest);
        return R.ok(questionPage);
    }

    /**
     * 分页获取题目列表（封装类）
     *
     * @param c2sQuestionQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<S2cQuestion>> listQuestionVOByPage(@RequestBody C2sQuestionQueryRequest c2sQuestionQueryRequest,
                                                                HttpServletRequest request) {
        long current = c2sQuestionQueryRequest.getCurrent();
        long size = c2sQuestionQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<Question> questionPage = questionSVC.page(new Page<>(current, size),
                questionSVC.getQueryWrapper(c2sQuestionQueryRequest));
        // 获取封装类
        return R.ok(questionSVC.getQuestionVOPage(questionPage, request));
    }

    /**
     * 分页获取当前登录用户创建的题目列表
     *
     * @param c2sQuestionQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/my/list/page/vo")
    public BaseResponse<Page<S2cQuestion>> listMyQuestionVOByPage(@RequestBody C2sQuestionQueryRequest c2sQuestionQueryRequest,
                                                                  HttpServletRequest request) {
        ThrowUtils.throwIf(c2sQuestionQueryRequest == null, ErrorCode.PARAMS_ERROR);
        // 补充查询条件，只查询当前登录用户的数据
        User loginUser = userService.getLoginUser(request);
        c2sQuestionQueryRequest.setUserId(loginUser.getId());
        long current = c2sQuestionQueryRequest.getCurrent();
        long size = c2sQuestionQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<Question> questionPage = questionSVC.page(new Page<>(current, size),
                questionSVC.getQueryWrapper(c2sQuestionQueryRequest));
        // 获取封装类
        return R.ok(questionSVC.getQuestionVOPage(questionPage, request));
    }

    /**
     * 编辑题目（给用户使用）
     *
     * @param c2sQuestionEditRequest
     * @param request
     * @return
     */
    @PostMapping("/edit")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> editQuestion(@RequestBody C2sQuestionEditRequest c2sQuestionEditRequest, HttpServletRequest request) {
        if (c2sQuestionEditRequest == null || c2sQuestionEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // todo 在此处将实体类和 DTO 进行转换
        Question question = new Question();
        BeanUtils.copyProperties(c2sQuestionEditRequest, question);
        List<String> tags = c2sQuestionEditRequest.getTags();
        if (tags != null) {
            question.setTags(JSONUtil.toJsonStr(tags));
        }
        // 数据校验
        questionSVC.validQuestion(question, false);
        User loginUser = userService.getLoginUser(request);
        // 判断是否存在
        long id = c2sQuestionEditRequest.getId();
        Question oldQuestion = questionSVC.getById(id);
        ThrowUtils.throwIf(oldQuestion == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可编辑
        if (!oldQuestion.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 操作数据库
        boolean result = questionSVC.updateById(question);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return R.ok(true);
    }


    @PostMapping("/search/page/vo")
    public BaseResponse<Page<S2cQuestion>> searchQuestionVOByPage(@RequestBody C2sQuestionQueryRequest c2sQuestionQueryRequest, HttpServletRequest request) {
        int size = c2sQuestionQueryRequest.getPageSize();
        ThrowUtils.throwIf(size > 200, ErrorCode.PARAMS_ERROR);
        // 使用模糊查询
        Page<Question> questionPage = questionSVC.page(new Page<>(1, size), questionSVC.getQueryWrapper(c2sQuestionQueryRequest));
        questionSVC.getQuestionVOPage(questionPage, request);
        return R.ok(questionSVC.getQuestionVOPage(questionPage, request));
    }

    @PostMapping("delete/batch")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> batchDeleteQuestions(@RequestBody C2sQuestionBatchDeleteRequest c2sQuestionBatchDeleteRequest) {
        ThrowUtils.throwIf(c2sQuestionBatchDeleteRequest == null, ErrorCode.PARAMS_ERROR);
        questionSVC.batchDeleteQuestions(c2sQuestionBatchDeleteRequest.getQuestionIdList());
        return R.ok(true);
    }
    // endregion
}
